package be.android.forap.crypto;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;

public class CryptoUtil{


	public static String getPublicKeyAlgorithm(int i){
		if(i==1)
			return "RSA_GENERAL";
		if(i==2)
			return "RSA_ENCRYPT";
		if(i==3)
			return "RSA_SIGN";
		if(i==16)
			return "ELGAMAL_ENCRYPT";
		if(i==17)
			return "DSA";
		if(i==18)
			return "EC";
		if(i==19)
			return "ECDSA";
		if(i==20)
			return "ELGAMAL_GENERAL";
		if(i==21)
			return "DIFFIE_HELLMAN";
		return "Unspecified algorithm";
	}

	public static String toHex(byte[] bytes) {
		BigInteger bi = new BigInteger(1, bytes);
		String nospace = String.format("%0" + (bytes.length << 1) + "X", bi);
		char[] stringArray = nospace.toCharArray(); 
		StringBuilder sb = new StringBuilder();

		int i = 0;
		while(i < stringArray.length) {
			sb.append(stringArray[i]);
			sb.append(stringArray[i+1]);
			sb.append(" ");
			i +=2;
		}
		return sb.toString();
	}
	
	public static String toHexNoSpaces(byte[] bytes) {
		BigInteger bi = new BigInteger(1, bytes);
		return String.format("%0" + (bytes.length << 1) + "X", bi);
	}

	public static long keyFromHex(String data) {
		int len = data.length();
		String s2 = data.substring(len - 8);
		String s1 = data.substring(0, len - 8);
		return (Long.parseLong(s1, 16) << 32) | Long.parseLong(s2, 16);
	}

	public static String getSmallFingerPrint(long keyId) {
		String fingerPrint = Long.toHexString(keyId & 0xffffffffL).toUpperCase();
		while (fingerPrint.length() < 8) {
			fingerPrint = "0" + fingerPrint;
		}
		return fingerPrint;
	}

	public static byte[] getBytesFromFile(File file) throws IOException {
		InputStream is = new FileInputStream(file);

		// Get the size of the file
		long length = file.length();

		if (length > Integer.MAX_VALUE) {
			// File is too large
		}

		// Create the byte array to hold the data
		byte[] bytes = new byte[(int)length];

		// Read in the bytes
		int offset = 0;
		int numRead = 0;
		while (offset < bytes.length
				&& (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
			offset += numRead;
		}

		// Ensure all the bytes have been read in
		if (offset < bytes.length) {
			throw new IOException("Could not completely read file "+file.getName());
		}

		// Close the input stream and return bytes
		is.close();
		return bytes;
	}
}